/**
 * API工具类 - 模拟携带openid请求后端接口
 * 提供统一的API请求接口和用户状态管理
 */

// API配置常量
const API_CONFIG = {
    // 后端接口基础URL
    BASE_URL: 'http://localhost:8080/api',
    // 认证相关接口
    LOGIN_URL: '/auth/login',
    LOGOUT_URL: '/auth/logout',
    REFRESH_TOKEN_URL: '/auth/refresh',
    
    // 用户相关接口
    USER_INFO_URL: '/user/info',
    USER_PROFILE_URL: '/user/profile',
    USER_PROGRESS_URL: '/user/progress',
    USER_STATS_URL: '/user/stats',
    
    // 学习相关接口
    TASK_COMPLETE_URL: '/task/complete',
    TASK_LIST_URL: '/task/list',
    STUDY_RECORD_URL: '/study/record',
    QUESTION_LIST_URL: '/question/list',
    
    // 文件上传接口
    UPLOAD_AVATAR_URL: '/upload/avatar',
    UPLOAD_FILE_URL: '/upload/file'
};

// 用户状态管理
const UserState = {
    isLoggedIn: false,
    openid: null,
    token: null,
    refreshToken: null,
    userInfo: null,
    studyProgress: null,
    lastLoginTime: null
};

// 请求状态管理
const RequestState = {
    isRequesting: false,
    requestQueue: [],
    retryCount: 0,
    maxRetries: 3
};

/**
 * 工具函数类
 */
class ApiUtils {
    
    /**
     * 显示提示信息
     * @param {string} message - 消息内容
     * @param {string} type - 消息类型 (info, success, warning, error)
     */
    static showMessage(message, type = 'info') {
        const timestamp = new Date().toLocaleTimeString();
        console.log(`[${timestamp}] [${type.toUpperCase()}] ${message}`);
        
        // 可以在这里集成UI提示组件，如toast
        if (typeof window.showToast === 'function') {
            window.showToast(message, type);
        }
    }

    /**
     * 获取URL参数
     * @param {string} name - 参数名
     * @returns {string|null} 参数值
     */
    static getUrlParameter(name) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(name);
    }

    /**
     * 生成随机openid
     * @returns {string} 生成的openid
     */
    static generateMockOpenid() {
        const timestamp = Date.now();
        const random = Math.random().toString(36).substring(2, 15);
        return `mock_openid_${timestamp}_${random}`;
    }

    /**
     * 模拟网络延迟
     * @param {number} ms - 延迟毫秒数
     * @returns {Promise} 延迟Promise
     */
    static delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    /**
     * 验证用户登录状态
     * @returns {boolean} 是否已登录
     */
    static validateLogin() {
        // 从URL参数获取
        const openid = this.getUrlParameter('openid');
        const token = this.getUrlParameter('token');
        
        // 从本地存储获取
        const storedToken = localStorage.getItem('user_token');
        const storedOpenid = localStorage.getItem('user_openid');
        
        if (openid && token) {
            UserState.openid = openid;
            UserState.token = token;
            UserState.isLoggedIn = true;
            return true;
        } else if (storedToken && storedOpenid) {
            UserState.openid = storedOpenid;
            UserState.token = storedToken;
            UserState.isLoggedIn = true;
            return true;
        }
        
        return false;
    }

    /**
     * 保存用户状态到本地存储
     */
    static saveUserState() {
        if (UserState.token) {
            localStorage.setItem('user_token', UserState.token);
        }
        if (UserState.openid) {
            localStorage.setItem('user_openid', UserState.openid);
        }
        if (UserState.userInfo) {
            localStorage.setItem('user_info', JSON.stringify(UserState.userInfo));
        }
    }

    /**
     * 清除用户状态
     */
    static clearUserState() {
        UserState.isLoggedIn = false;
        UserState.openid = null;
        UserState.token = null;
        UserState.refreshToken = null;
        UserState.userInfo = null;
        UserState.studyProgress = null;
        UserState.lastLoginTime = null;
        
        localStorage.removeItem('user_token');
        localStorage.removeItem('user_openid');
        localStorage.removeItem('user_info');
    }

    /**
     * 模拟API请求函数
     * @param {string} url - 请求URL
     * @param {Object} options - 请求选项
     * @returns {Promise} 请求结果
     */
    static async mockApiRequest(url, options = {}) {
        // 模拟网络错误 (5%概率)
        if (Math.random() < 0.05) {
            throw new Error('网络连接失败');
        }
        
        // 模拟网络延迟 (200-700ms)
        await this.delay(Math.random() * 500 + 200);
        
        // 根据URL返回不同的模拟数据
        return this.generateMockResponse(url, options);
    }

    /**
     * 生成模拟响应数据
     * @param {string} url - 请求URL
     * @param {Object} options - 请求选项
     * @returns {Object} 模拟响应
     */
    static generateMockResponse(url, options = {}) {
        const timestamp = new Date().toISOString();
        
        // 认证相关接口
        if (url.includes('/auth/login')) {
            const loginData = options.body ? JSON.parse(options.body) : {};
            return {
                success: true,
                data: {
                    token: 'mock_token_' + Date.now(),
                    refreshToken: 'mock_refresh_' + Date.now(),
                    userInfo: {
                        id: 1,
                        openid: loginData.openid || UserState.openid,
                        nickname: '测试用户',
                        avatar: 'http://gips3.baidu.com/it/u=3886271102,3123389489&fm=3028&app=3028&f=JPEG&fmt=auto?w=1280&h=960',
                        email: 'test@example.com',
                        phone: '138****8888',
                        role: 'student'
                    }
                },
                message: '登录成功'
            };
        }
        
        // 用户信息接口
        if (url.includes('/user/info')) {
            return {
                success: true,
                data: {
                    id: 1,
                    openid: UserState.openid,
                    nickname: '苟娅琳',
                    avatar: 'http://gips3.baidu.com/it/u=3886271102,3123389489&fm=3028&app=3028&f=JPEG&fmt=auto?w=1280&h=960',
                    email: 'gouyalin@example.com',
                    phone: '138****8888',
                    role: 'student',
                    lastLoginTime: timestamp,
                    createdAt: '2024-01-01T00:00:00.000Z'
                },
                message: '获取用户信息成功'
            };
        }
        
        // 学习进度接口
        if (url.includes('/user/progress')) {
            return {
                success: true,
                data: {
                    openid: UserState.openid,
                    totalQuestions: 1250,
                    completedQuestions: 856,
                    accuracy: 0.78,
                    studyDays: 45,
                    currentStreak: 7,
                    lastStudyDate: timestamp,
                    weeklyProgress: [65, 72, 68, 75, 80, 78, 82],
                    monthlyProgress: [320, 345, 378, 402]
                },
                message: '获取学习进度成功'
            };
        }
        
        // 任务完成接口
        if (url.includes('/task/complete')) {
            const taskData = options.body ? JSON.parse(options.body) : {};
            return {
                success: true,
                data: {
                    taskId: taskData.taskId,
                    taskName: taskData.taskName,
                    completed: true,
                    completedAt: timestamp,
                    points: 10,
                    experience: 50,
                    message: '任务完成！获得10积分和50经验值'
                },
                message: '任务完成成功'
            };
        }
        
        // 学习统计接口
        if (url.includes('/user/stats')) {
            return {
                success: true,
                data: {
                    openid: UserState.openid,
                    totalStudyTime: 12560, // 分钟
                    averageAccuracy: 0.78,
                    rank: 156,
                    totalUsers: 1250,
                    weeklyProgress: [65, 72, 68, 75, 80, 78, 82],
                    monthlyProgress: [320, 345, 378, 402],
                    achievements: [
                        { id: 1, name: '学习达人', description: '连续学习7天', unlocked: true },
                        { id: 2, name: '答题高手', description: '正确率超过80%', unlocked: true },
                        { id: 3, name: '坚持不懈', description: '学习超过30天', unlocked: false }
                    ]
                },
                message: '获取统计数据成功'
            };
        }
        
        // 任务列表接口
        if (url.includes('/task/list')) {
            return {
                success: true,
                data: {
                    tasks: [
                        { id: 1, name: '每日一练', description: '完成今日练习', points: 10, completed: false },
                        { id: 2, name: '历年真题', description: '完成一套历年真题', points: 20, completed: false },
                        { id: 3, name: '模拟试题', description: '完成模拟考试', points: 30, completed: false },
                        { id: 4, name: '做题记录', description: '查看做题历史', points: 5, completed: false }
                    ]
                },
                message: '获取任务列表成功'
            };
        }
        
        // 默认响应
        return {
            success: false,
            message: '未知接口',
            data: null
        };
    }

    /**
     * 通用API请求函数
     * @param {string} url - 请求URL
     * @param {Object} options - 请求选项
     * @returns {Promise} 请求结果
     */
    static async apiRequest(url, options = {}) {
        // 添加认证头
        if (UserState.token) {
            options.headers = {
                ...options.headers,
                'Authorization': `Bearer ${UserState.token}`
            };
        }
        
        // 添加openid参数
        if (UserState.openid && !url.includes('openid=')) {
            const separator = url.includes('?') ? '&' : '?';
            url += `${separator}openid=${UserState.openid}`;
        }
        
        try {
            const response = await this.mockApiRequest(url, options);
            
            if (response.success) {
                return response;
            } else {
                throw new Error(response.message || '请求失败');
            }
        } catch (error) {
            this.showMessage(`API请求失败: ${error.message}`, 'error');
            throw error;
        }
    }

    /**
     * 获取用户信息
     * @returns {Promise} 用户信息
     */
    static async fetchUserInfo() {
        try {
            this.showMessage('正在获取用户信息...', 'info');
            
            const response = await this.apiRequest(API_CONFIG.USER_INFO_URL, {
                method: 'GET'
            });
            
            UserState.userInfo = response.data;
            this.saveUserState();
            
            this.showMessage('用户信息获取成功', 'success');
            return response.data;
        } catch (error) {
            this.showMessage(`获取用户信息失败: ${error.message}`, 'error');
            throw error;
        }
    }

    /**
     * 获取学习进度
     * @returns {Promise} 学习进度
     */
    static async fetchStudyProgress() {
        try {
            this.showMessage('正在获取学习进度...', 'info');
            
            const response = await this.apiRequest(API_CONFIG.USER_PROGRESS_URL, {
                method: 'GET'
            });
            
            UserState.studyProgress = response.data;
            
            this.showMessage('学习进度获取成功', 'success');
            return response.data;
        } catch (error) {
            this.showMessage(`获取学习进度失败: ${error.message}`, 'error');
            throw error;
        }
    }

    /**
     * 完成任务
     * @param {string} taskId - 任务ID
     * @param {string} taskName - 任务名称
     * @returns {Promise} 完成结果
     */
    static async completeTask(taskId, taskName) {
        try {
            this.showMessage(`正在完成任务: ${taskName}...`, 'info');
            
            const taskData = {
                openid: UserState.openid,
                taskId: taskId,
                taskName: taskName,
                completedAt: new Date().toISOString()
            };
            
            const response = await this.apiRequest(API_CONFIG.TASK_COMPLETE_URL, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(taskData)
            });
            
            this.showMessage(`任务完成: ${response.data.message}`, 'success');
            return response.data;
        } catch (error) {
            this.showMessage(`任务完成失败: ${error.message}`, 'error');
            throw error;
        }
    }

    /**
     * 获取学习统计
     * @returns {Promise} 学习统计
     */
    static async fetchStudyStats() {
        try {
            this.showMessage('正在获取学习统计...', 'info');
            
            const response = await this.apiRequest(API_CONFIG.USER_STATS_URL, {
                method: 'GET'
            });
            
            this.showMessage('学习统计获取成功', 'success');
            return response.data;
        } catch (error) {
            this.showMessage(`获取学习统计失败: ${error.message}`, 'error');
            throw error;
        }
    }

    /**
     * 用户登录
     * @param {string} openid - 用户openid
     * @returns {Promise} 登录结果
     */
    static async login(openid) {
        try {
            this.showMessage('正在验证用户身份...', 'info');
            
            const loginData = {
                openid: openid,
                timestamp: Date.now(),
                device: 'web'
            };
            
            const response = await this.mockApiRequest(API_CONFIG.LOGIN_URL, {
                method: 'POST',
                body: JSON.stringify(loginData)
            });
            
            if (response.success) {
                UserState.isLoggedIn = true;
                UserState.openid = openid;
                UserState.token = response.data.token;
                UserState.refreshToken = response.data.refreshToken;
                UserState.userInfo = response.data.userInfo;
                UserState.lastLoginTime = new Date().toISOString();
                
                this.saveUserState();
                
                this.showMessage('登录成功', 'success');
                return response.data;
            } else {
                throw new Error(response.message || '登录失败');
            }
        } catch (error) {
            this.showMessage(`登录失败: ${error.message}`, 'error');
            throw error;
        }
    }

    /**
     * 用户登出
     * @returns {Promise} 登出结果
     */
    static async logout() {
        try {
            this.showMessage('正在登出...', 'info');
            
            await this.apiRequest(API_CONFIG.LOGOUT_URL, {
                method: 'POST'
            });
            
            this.clearUserState();
            
            this.showMessage('登出成功', 'success');
            return true;
        } catch (error) {
            this.showMessage(`登出失败: ${error.message}`, 'error');
            // 即使API调用失败，也清除本地状态
            this.clearUserState();
            throw error;
        }
    }
}

// 导出到全局作用域
window.API_CONFIG = API_CONFIG;
window.UserState = UserState;
window.ApiUtils = ApiUtils;

// 兼容性导出
window.mockApiRequest = ApiUtils.mockApiRequest.bind(ApiUtils);
window.showMessage = ApiUtils.showMessage.bind(ApiUtils); 